import { getAllParentCategory, getSubCategoryByParentId } from '@/api/api';

export async function getCate(){
  try {
    // 显示加载中提示
    wx.showLoading({
      title: '加载分类数据中...',
    });
    
    // 获取所有父分类
    const parentRes = await getAllParentCategory();
    if (parentRes.code !== 200) {
      wx.showToast({
        title: '获取父分类失败',
        icon: 'none'
      });
      return;
    }
    
    const parentList = parentRes.data || [];
    // 并发获取所有子分类
    const childrenPromises = parentList.map((parent) =>
      getSubCategoryByParentId(parent.id)
    );
    const childrenResults = await Promise.all(childrenPromises);

    // 组装 categoryList
    const categoryList = parentList.map((parent, idx) => ({
      text: parent.categoryName,
      dot: false,
      disabled: false,
      id: parent.id,
      children: (childrenResults[idx].data || []).map((child) => ({
        text: child.categoryName,
        id: child.id
      }))
    }));

    //存入app.js
    const app = getApp();
    app.categoryList = categoryList;
    
  } catch (error) {
    console.error('获取分类数据异常:', error);
    wx.showToast({
      title: '获取分类数据失败',
      icon: 'none'
    });
  } finally {
    // 隐藏加载中提示
    wx.hideLoading();
  }
}